package com.andrew.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.andrew.entity.Order;
import com.andrew.entity.OrderDetail;
import com.andrew.entity.OrderDetailForAdmin;
import com.andrew.service.OrderService;
import com.andrew.service.impl.OrderServiceImpl;
import com.google.gson.Gson;

public class FetchOrderDetailsServlet extends HttpServlet {
	private OrderService orderService=new OrderServiceImpl();
	private Gson gson=new Gson();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		
		String orderId=req.getParameter("OrderId");	
		try {
			List<OrderDetail> orderDetailsList = orderService.getOrderByOrderId(orderId).getOrderDetailsList();
			List<OrderDetailForAdmin> list=new ArrayList<>();
			
			for(OrderDetail orderDetail:orderDetailsList) {
				OrderDetailForAdmin od=new OrderDetailForAdmin();
				od.setAuthor(orderDetail.getBook().getAuthor());
				od.setBookId(orderDetail.getBook().getBookId());
				od.setBookName(orderDetail.getBook().getBookName());
				od.setPrice(orderDetail.getBook().getPrice());
				od.setQuantity(orderDetail.getQuantity());
				list.add(od);
			}
			
			String json=gson.toJson(list);
			
			resp.getWriter().write(json);
			
			System.out.println("enterFetch");
			System.out.println(json);
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
}
